/*
 *  Copyright 2019-2023 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.modules.biz.domain.Universities;
import me.zhengjie.modules.biz.domain.resp.UniversitiesDetailResp;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.biz.service.UniversitiesService;
import me.zhengjie.modules.biz.domain.vo.UniversitiesQueryCriteria;
import me.zhengjie.modules.biz.mapper.UniversitiesMapper;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.io.File;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;
import redis.clients.jedis.Jedis;

import static me.zhengjie.modules.biz.constant.GlobalConstant.*;

/**
 * @description 服务实现
 * @author yiwei.he
 * @date 2024-03-11
 **/
@Service
@RequiredArgsConstructor
public class UniversitiesServiceImpl extends ServiceImpl<UniversitiesMapper, Universities> implements UniversitiesService {

    private final UniversitiesMapper universitiesMapper;

    @Value(value = "${url.default}")
    private String logoUrl;

    @Override
    public PageResult<Universities> queryAll(UniversitiesQueryCriteria criteria, Page<Object> page) {
        IPage<Universities> list = universitiesMapper.findAll(criteria, page);
        // 没有上传院校logo的使用默认图片，并将 content 字段剪切为 20 个字符长度，标签补充专科、本科，公办、民办
        list.getRecords().forEach(u -> {
            if (StringUtils.isBlank(u.getLogo())) {
                u.setLogo(logoUrl + DEFAULT_LOGO);
            }
            if (StringUtils.isNotBlank(u.getContent()) && u.getContent().length() > 20) {
                u.setContent(u.getContent().substring(0, 20));
            }
            String quality = (u.getUniversityQuality() == 0) ? GOVERNMENT : INDEPENDENT;
            String type = (u.getUniversityType() == 0) ? BK : ZK;
            String labels = quality + "," + type + (StringUtils.isBlank(u.getLabels()) ? "" :  "," + u.getLabels()) ;
            u.setLabels(labels);
        });
        return PageUtil.toPage(list);
    }

    @Override
    public PageResult<Universities> list(UniversitiesQueryCriteria criteria, Page<Object> page) {
        IPage<Universities> list = universitiesMapper.list(criteria, page);
        // 没有上传院校logo的使用默认图片
        list.getRecords().forEach(u -> {
            if (StringUtils.isBlank(u.getLogo())) {
                u.setLogo(logoUrl + DEFAULT_LOGO);
            }
            if(u.getLabels() != null){
                u.setLabelList(Arrays.asList(u.getLabels().split(",")));
            }
        });
        return PageUtil.toPage(list);
    }

    @Override
    public List<Universities> queryAll(UniversitiesQueryCriteria criteria){
        return universitiesMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Universities resources) {
        save(resources);

        // 连接到 Redis 服务器
        Jedis jedis = new Jedis("127.0.0.1", 6379);

        List<String> delKeys = new ArrayList<>();
        delKeys.add(TZ_RECOMMEND_LIST);
        delKeys.add(TZ_RECOMMEND);

        // 遍历前缀集合
        for (String prefix : delKeys) {
            // 获取匹配的键
            Set<String> keys = jedis.keys(prefix + "*");

            // 删除匹配的键
            for (String key : keys) {
                jedis.del(key);
            }
        }
        // 关闭连接
        jedis.close();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Universities resources) {
        if(resources.getLabels() != null){
            resources.setLabels(resources.getLabels().replace("，",","));
        }
        Universities universities = getById(resources.getId());
        universities.copy(resources);
        saveOrUpdate(universities);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Universities> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Universities universities : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("院校名称", universities.getName());
            map.put("院校代码", universities.getInstitutionCode());
            map.put("院校区域", universities.getAddress());
            map.put("院校logo", universities.getLogo());
            map.put("院校标签", universities.getLabels());
            map.put("办学层次【0：本科 1：专科】", universities.getUniversityType());
            map.put("办学性质【0：公办 1：民办】", universities.getUniversityQuality());
            map.put("删除【0：未删除 1：删除】", universities.getIsDelete());
            map.put("院校类别【1：统招 2：统招+专升本（部分本科院校） 3：统招+单招（专科院校）】", universities.getCategory());
            map.put("学校概况", universities.getProfile());
            map.put("学校综合排名", universities.getRanking());
            map.put("院校官网", universities.getWebsite());
            map.put("招生办官网", universities.getEnrollWebsite());
            map.put("招生办电话 ", universities.getMobile());
            map.put("院校详情", universities.getContent());
            map.put("院系数", universities.getDepartment());
            map.put("博士点", universities.getDoctor());
            map.put("硕士点", universities.getMaster());
            map.put("所属地区", universities.getBelongarea());
            map.put("创建时间", universities.getCreateTime());
            map.put("修改时间", universities.getUpdateTime());
            map.put("说明", universities.getRemark());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 查询院校详情
     * @param universityName
     * @return
     */
    @Override
    public UniversitiesDetailResp queryByName(String universityName) {
        UniversitiesDetailResp resp = universitiesMapper.queryByName(universityName);
        if(resp.getLogo() == null){
            resp.setLogo(logoUrl + DEFAULT_LOGO);
        }
        return resp;
    }
}